import Taro from "@tarojs/taro";
import {DAIYL_LOAD, DAIYL_LOADING, DAIYL_NOMORE, DAIYL_RESET, DAIYL_HOME_LIST, DAIYL_RESET_LIST, DAIYL_KEYWORD} from '../constants/daily'
import {asyncGoodList, asyncHomeGoodList} from "../api/good";

// 重置每日鲜果的状态
export const dailyReset = () => {
  return {
    type: DAIYL_RESET
  }
}

// 加载每日鲜果首页数据
export const loadHomeList = (homeList) => {
  return {
    type: DAIYL_HOME_LIST,
    homeList
  }
}
export const load = (data) => {
  return {
    type: DAIYL_LOAD,
    data
  }
}

export const setLoading = (bool) => {
  return {
    type: DAIYL_LOADING,
    loading: bool
  }
}

export const nomore = () => {
  return {
    type: DAIYL_NOMORE
  }
}
// 设置关键词
export const setKeyword = (word) => {
  return {
    type: DAIYL_KEYWORD,
    data: word
  }
}

// 对列表进行重置 用于搜索
export const reSetList = () => {
  return {
    type: DAIYL_RESET_LIST
  }
}

// 异步的action 加载首页数据
export function asyncLoadHomeDaily () {
  return (dispatch, getState) => {
    const { token } = getState().user
    const { shop_id } = getState().shop
    if (!token || !shop_id) return // TODO 二者不在的处理

    dispatch(setLoading(true)) // 设置状态 ... 开始加载
    asyncHomeGoodList(token, shop_id, 1).then(({data, status}) => {
      console.log(data)
      if (status) {
        dispatch(loadHomeList(data))
      }
    })
  }
}

// 异步的action 加载分页数据
export function asyncLoadDaily () {
  return (dispatch, getState) => {
    const { page, search } = getState().daily
    const { token } = getState().user
    const { shop_id } = getState().shop
    if (!token || !shop_id) return // TODO 二者不在的处理
    const nextPage = page + 1

    dispatch(setLoading(true)) // 设置状态 ... 开始加载
    asyncGoodList(token, shop_id, 1, page, search).then(({data, status}) => {
      console.log(data)
      if (status) {
        dispatch(load({
          list: data.data,
          page: nextPage,
          nomore: data.data.length < 5
        }))
        dispatch(setLoading(false)) // 设置状态 ... 加载完毕
      }
    })
  }
}
